package com.sgb.goods.view.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.blankj.utilcode.util.ColorUtils;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.goods.BR;
import com.sgb.goods.R;
import com.sgb.goods.databinding.GoodsActivityAddStorageBinding;
import com.sgb.goods.entity.StorageManageEntity;
import com.sgb.goods.entity.inquiry.MapLongAndLatEntity;
import com.sgb.goods.utils.Constants;
import com.sgb.goods.utils.base.BaseActivity;
import com.sgb.goods.viewmodel.AddStorageViewModel;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.MToast;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.swgk.core.view.areapopup.AddressEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 描述：商品-添加仓储
 *
 * @author qiangHeNoo
 * <p>
 * 时间：2021.12.01
 */
@Route(path = Constants.ARouter.AR_ADD_STORAGE)
public class GoodsAddStorageActivity extends BaseActivity<GoodsActivityAddStorageBinding, AddStorageViewModel> implements ItemInputTextView.OnWholeItemClickListener {
    /**
     * 一级联动数据
     */
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    /**
     * 二级联动数据
     */
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    /**
     * 三级联动数据
     */
    private List<List<List<AddressEntity>>> opt3;
    /**
     * 区域列表
     */
    private List<List<AddressEntity>> areaList;
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private Thread thread;
    private double locCurrentLat = 0;
    private double locCurrentLong = 0;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private boolean isLoaded = false;
    private String detailsAddress;
    private String provinceNo;
    private String cityNo;
    private String districtNo;
    private static final int REQUEST_CODE = 101;


    public static void start(Context context, StorageManageEntity entity) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        intent.setClass(context, GoodsAddStorageActivity.class);
        bundle.putSerializable("entity", entity);
        intent.putExtras(bundle);
        if (entity != null) {
            intent.putExtra("provinceNo", entity.getProvinceNo());
            intent.putExtra("cityNo", entity.getCityNo());
            intent.putExtra("districtNo", entity.getDistrictNo());
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.goods_activity_add_storage;
    }

    @Override
    protected void initViewModel() {
        mViewModel = createViewModel(AddStorageViewModel.class, BR.viewModel);
    }

    @Override
    protected void initObserve() {
        mViewModel.addressEntityLiveData.observe(this, this::initAddressData);
        mViewModel.onFinishActivity.observe(this, aBoolean -> {
            if (aBoolean) {
                mViewModel.finishActivity(998);
            }
        });
        mViewModel.andLatEntityMutableLiveData.observe(this, this::getLocationLL);
    }

    @Override
    protected void init() {
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        initView();
    }

    protected void initView() {
        StorageManageEntity entity = (StorageManageEntity) getIntent().getSerializableExtra("entity");
        provinceNo = getIntent().getStringExtra("provinceNo");
        cityNo = getIntent().getStringExtra("cityNo");
        districtNo = getIntent().getStringExtra("districtNo");
        if (entity != null) {
            mViewModel.storageManEntity.set(entity);
        }
        if (entity == null) {
            mDataBinding.head.title.setText("新增仓储");
            mDataBinding.goodsConfirm.setText("提交");
        } else {
            mDataBinding.head.title.setText("编辑仓储");
            mDataBinding.goodsConfirm.setText("保存");
            mDataBinding.goodsItemTvArea.setContent(entity.getAddress());
        }
        if (entity != null) {
            if (!TextUtils.isEmpty(entity.getLatitude()) && !TextUtils.isEmpty(entity.getLongitude())) {
                locCurrentLat = Double.parseDouble(entity.getLatitude());
                locCurrentLong = Double.parseDouble(entity.getLongitude());
            } else {
                mViewModel.getLocationLL(provinceNo, cityNo, districtNo);
            }
        }
    }

    @Override
    protected void initListener() {
        mDataBinding.head.ivBack.setOnClickListener(v -> finish());
        mDataBinding.goodsConfirm.setOnClickListener(v -> sava());
        mDataBinding.goodsItemTvArea.setOnWholeItemClickListener(this);
        mDataBinding.goodsItemTvAddress.setOnWholeItemClickListener(this);
    }

    private void sava() {
        if (TextUtils.isEmpty(mDataBinding.goodsItemTvName.getContent())) {
            MToast.showToast(GoodsAddStorageActivity.this, "请输入仓储名称");
            return;
        }
        if (TextUtils.isEmpty(mDataBinding.goodsItemTvArea.getContent())) {
            MToast.showToast(GoodsAddStorageActivity.this, "请选择省市区");
            return;
        }
        if (TextUtils.isEmpty(mDataBinding.goodsItemTvAddress.getContent())) {
            MToast.showToast(GoodsAddStorageActivity.this, "请填写详细地址");
            return;
        }
        Objects.requireNonNull(mViewModel.storageManEntity.get()).setAddress(mDataBinding.goodsItemTvArea.getContent());
        mViewModel.save();
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void OnWholeItemClick(View view) {
        if(view.getId() == R.id.goods_item_tv_area) {
            if (addressEntityList != null) {
                showCityPop();
            } else {
                mViewModel.getAddressList();
            }
        } else if(view.getId() == R.id.goods_item_tv_address) {
            if (!TextUtils.isEmpty(mDataBinding.goodsItemTvArea.getContent())) {
                Intent intent = new Intent();
                intent.setClass(GoodsAddStorageActivity.this, SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "选择定位地址");
                intent.putExtra(SelectAddressActivity.LATITUDE, locCurrentLat);
                intent.putExtra(SelectAddressActivity.LONGTITUDE, locCurrentLong);
                startActivityForResult(intent, REQUEST_CODE);
            } else {
                Toast.makeText(GoodsAddStorageActivity.this, "请选择省市区", Toast.LENGTH_SHORT).show();
            }
        }
    }


    private void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        this.addressEntityList = data;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    private void showCityPop() {
        CityPickView cityOption = new CityPickBuilder(GoodsAddStorageActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String areaName;
                if (opt3.get(options1).get(options2).get(options3) == null) {
                    areaName = "";
                } else {
                    areaName = opt3.get(options1).get(options2).get(options3).getName();
                    cityPosition3 = options3;
                    //区
                    Objects.requireNonNull(mViewModel.storageManEntity.get()).setDistrictName(areaName);
                    Objects.requireNonNull(mViewModel.storageManEntity.get()).setDistrictNo(opt3.get(options1).get(options2).get(options3).getNo());
                    districtNo = opt3.get(options1).get(options2).get(options3).getNo();
                }
                String content = addressEntityList.get(options1).getName() + "-" + opt2.get(options1).get(options2).getName() + "-" + areaName;
                mDataBinding.goodsItemTvArea.setContent(content);
                cityPosition1 = options1;
                cityPosition2 = options2;
                //省市
                Objects.requireNonNull(mViewModel.storageManEntity.get()).setProvinceName(addressEntityList.get(options1).getName());
                Objects.requireNonNull(mViewModel.storageManEntity.get()).setProvinceNo(addressEntityList.get(options1).getId());
                provinceNo = addressEntityList.get(options1).getId();
                //市
                Objects.requireNonNull(mViewModel.storageManEntity.get()).setCityName(opt2.get(options1).get(options2).getName());
                Objects.requireNonNull(mViewModel.storageManEntity.get()).setCityNo(opt2.get(options1).get(options2).getNo());
                cityNo = opt2.get(options1).get(options2).getNo();
                mViewModel.getLocationLL(provinceNo, cityNo, districtNo);
            }
        }).setCancelColor(ColorUtils.getColor(R.color.color_666666)).setTitleText("选择仓储地区").setTitleColor(ColorUtils.getColor(R.color.color_969696)).
                build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    private void getLocationLL(MapLongAndLatEntity data) {
        locCurrentLat = Double.parseDouble(data.getLat());
        locCurrentLong = Double.parseDouble(data.getLng());
    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {
                        thread = new Thread(() -> initJsonData());
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    break;
                default:
                    break;
            }
        }
    };

    private void initJsonData() {
        for (int i = 0; i < addressEntityList.size(); i++) {
            if (!TextUtils.isEmpty(provinceNo)) {
                if (addressEntityList.get(i).getId().equals(provinceNo)) {
                    cityPosition1 = i;
                }
            }
            areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {
                if (!TextUtils.isEmpty(cityNo)) {
                    if (addressEntityList.get(i).getChildren().get(j).getId().equals(cityNo)) {
                        cityPosition2 = j;
                    }
                }
                List<AddressEntity> cityAreaList = new ArrayList<>();
                List<AddressEntity> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                    if (!TextUtils.isEmpty(districtNo)) {
                        for (int k = 0; k < children.size(); k++) {
                            if (children.get(k).getId().equals(districtNo)) {
                                cityPosition3 = k;
                            }
                        }
                    }
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && data != null) {
            locCurrentLat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
            locCurrentLong = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
            detailsAddress = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
            mDataBinding.goodsItemTvAddress.setContent(detailsAddress);
        }
    }

}
